#include "vedio.h"
#include "ui_vedio.h"
#include <QPixmap>
#include <QFileDialog>
#include <QDateTime>
#include <QMessageBox>

Vedio::Vedio(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Vedio)
{
    ui->setupUi(this);

    // 初始化网络管理器
    networkManager = new QNetworkAccessManager(this);
    networkReply = nullptr;

    // 初始化状态变量
    totalLen = 0;
    currentLen = 0;
    statu = 0;

    // 禁用停止按钮
    ui->stopButton->setEnabled(false);

    // 初始化URL输入框
    urlLineEdit = ui->urlLineEdit;

    // 连接截屏按钮信号槽
    connect(ui->screenshotButton, &QPushButton::clicked,
            this, &Vedio::on_screenshotButton_clicked);
}

Vedio::~Vedio()
{
    delete ui;
}

void Vedio::on_startButton_clicked()
{
    // 禁用开始按钮，启用停止按钮
    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);

    // 创建URL并发送GET请求
    QString httpUrl = urlLineEdit->text();
    if(httpUrl.isEmpty()) {
        httpUrl = "http://192.168.253.128:8080/?action=stream";
    }
    networkReply = networkManager->get(QNetworkRequest(QUrl(httpUrl)));

    // 连接信号槽
    connect(networkReply, &QNetworkReply::readyRead, this, &Vedio::readHttpCameraData);
    connect(networkReply, &QNetworkReply::finished, [=]() {
        qDebug() << "Request finished";
        ui->startButton->setEnabled(true);
        ui->stopButton->setEnabled(false);
    });
}

void Vedio::on_stopButton_clicked()
{
    // 停止接收数据
    if (networkReply) {
        networkReply->abort();
        networkReply->deleteLater();
        networkReply = nullptr;
    }

    // 重置UI状态
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
}

void Vedio::on_screenshotButton_clicked()
{
    // 检查是否有有效图像
    if (image.isNull()) {
        QMessageBox::warning(this, "警告", "没有视频画面可截取");
        return;
    }

    // 获取当前时间作为文件名
    QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss");
    QString defaultName = QString("截图_%1.png").arg(timestamp);

    // 弹出文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(this, "保存截图",
                                                  QDir::homePath() + "/" + defaultName,
                                                  "PNG图像 (*.png);;JPEG图像 (*.jpg *.jpeg)");

    if(fileName.isEmpty()) {
        return; // 用户取消保存
    }

    // 从label获取当前显示的图像并保存
    QPixmap screenshot = *ui->label->pixmap();
    if(!screenshot.isNull() && screenshot.save(fileName)) {
        QMessageBox::information(this, "成功", "截图已保存到: " + fileName);
    } else {
        QMessageBox::critical(this, "错误", "截图保存失败");
    }
}

void Vedio::readHttpCameraData()
{
    QByteArray boundary;
    QByteArray contentTypeLine;
    QByteArray contentLenghtLine;
    QByteArray blankSpaceLine;

    while (networkReply->bytesAvailable() > 0) {
        switch (statu) {
        case 0: // 初始状态
            boundary = networkReply->readLine();
            statu = 2;
            break;

        case 2: // 读取内容类型和长度
            contentTypeLine = networkReply->readLine();
            contentLenghtLine = networkReply->readLine();
            blankSpaceLine = networkReply->readLine();

            // 解析内容长度
            sscanf(contentLenghtLine.data(), "Content-Length: %d\r\n", &totalLen);
            buf.resize(totalLen);
            currentLen = 0;
            statu = 3;
            break;

        case 3: // 读取图片数据
            len = networkReply->read(buf.data() + currentLen, totalLen - currentLen);
            currentLen += len;

            if (currentLen == totalLen) {
                // 图片数据接收完成，加载图片
                image.loadFromData(buf);
                update(); // 触发paintEvent
                statu = 4;
            }
            break;

        case 4: // 读取结束边界
            blankSpaceLine = networkReply->readLine();
            boundary = networkReply->readLine();
            currentLen = 0;
            statu = 2;
            break;
        }
    }
}

void Vedio::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);

    // 确保image有效
    if (!image.isNull()) {
        QImage i = image.scaled(ui->label->size(), Qt::KeepAspectRatio);
        ui->label->setPixmap(QPixmap::fromImage(i));
    }
}